package com.example.login_demo.data;

import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.rdb.*;
import ohos.data.resultset.ResultSet;

import java.sql.ResultSetMetaData;

public class DataManager {





    public Context mContext;
    private RdbStore store;

    /**
     * 单例模式获得操作数据库对象
     *
     * @return
     */
    public static DataManager getInstance() {
        return manager;
    }

    //多线程中要被共享的使用volatile关键字修饰
    private volatile static DataManager manager = new DataManager();


    public void init(Context context) {
        this.mContext = context;
    }
    /**
     * 判断是否有存在数据库，如果没有则创建
     *
     * @return
     */
    public RdbStore getDaoMaster() {
        if (store == null) {
            synchronized (DataManager.class) {
                StoreConfig config = StoreConfig.newDefaultConfig("RdbStoreTest.db");
                DatabaseHelper helper = new DatabaseHelper(mContext);
                store = helper.getRdbStore(config, 1, callback, null);
            }
        }
        return store;
    }


    /**
     * 创建表
     */
    private static final RdbOpenCallback callback = new RdbOpenCallback() {
        @Override
        public void onCreate(RdbStore store) {
            store.executeSql("CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER, salary REAL, blobType BLOB)");
        }
        @Override
        public void onUpgrade(RdbStore store, int oldVersion, int newVersion) {
        }
    };

    /**
     * 插入数据
     */
    public void insert(){
        getDaoMaster();
        ValuesBucket values = new ValuesBucket();
        values.putInteger("id", 1);
        values.putString("name", "zhangsan");
        values.putInteger("age", 18);
        values.putDouble("salary", 100.5);
        values.putByteArray("blobType", new byte[] {1, 2, 3});
        long id = store.insert("test", values);    }



    /**
     * 查询数据
     */
    public void query(){
        getDaoMaster();
        String[] columns = new String[] {"id", "name", "age", "salary"};
        RdbPredicates rdbPredicates = new RdbPredicates("test").equalTo("age", 18).orderByAsc("salary");
        ResultSet resultSet = store.query(rdbPredicates, columns);

        while(resultSet.goToNextRow()){

        }


    }

}
